﻿module Sustainalytics.Screening {

    import Common = Sustainalytics.Common;

    export interface IScreeningToolControllerScope extends ng.IScope {
        tool: any;
        currentSelection: string;
        selectCriteria: any;
        getTypeSevenSelectedItemsNames: () => void;
        getTypeSevenItemName: (item: string) => string;
        selectedCriteria: SelectedCriteriaDto;
        currentFilter: ScreeningToolFilter;
        applyCurrentFilter: (filter: ScreeningToolFilter) => void;
        currentCriteriaTypeOne: CriteriaTypeOne;
        currentCriteriaTypeThree: CriteriaTypeThree;
        currentCriteriaTypeSix: CriteriaTypeSix;
        currentCriteriaTypeFive: CriteriaTypeFive;
        currentCriteriaTypeSeven: CriteriaTypeSeven;
        tabs: CriteriaTabs[];

        gcSelectedItems: any;

        criteriaTypeOneChart: any;
        criteriaTypeSixChart: any;
        addSelectedCriteria: any;
        updateSelectedCriteria: any;
        selectedCriteriaScore: any;
        tabChanged: any;
        userTabChanged: any;

        portfolios: any;
        currentPortfolio: any;
        currentUniverse: any;
        currentPortfolioOrUniverse: any;
        currentPeerGroup: any;
        currentRegion: any;
        currentCountry: any;
        currentCompanyType: any;

        sortableOptions: any;
        deleteCriteria: any;
        updateCriteria: any;
        selectedFilterCriteria: SelectedCriteriaDto;
        baseCriteriaList: BaseCriteria[];
        loadBaseCriteriaList: any;
        loadBaseCriteria: any;
        baseCriteriaSelected: any;
        searchText: string;
        allCriteriaComputed: () => boolean;
        deleteSelectedItems: (item: string) => void;
        deleteCriteriaTypeSevenSelectedItems: (item: string) => void;
        addItemToSelectedItems: (item: string) => void;
        addCriteriaTypeSevenItemToSelectedItems: (item: string) => void;
        searchInCollection: () => void;
        loadCriteriaTypeThreeCollectionItems: (loadMore: boolean) => void;
        loadCriteriaTypeSevenCollectionItems: (loadMore: boolean) => void;
        initSignalR: any;
        criteriaHub: ProcessHubProxy;
        open: (size) => void;
        lastUsedFilters: any;
        asyncLoadFiltersOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        ensureLatestFilters: (any) => void;
        runCurrentCriteria: () => ng.IPromise<{}>;
        runCriteria: (filterId: string) => ng.IPromise<{}>;
        exportCriteria: () => void;
        getResultOutput: (pageIndex?: number, pageSize?: number) => ng.IPromise<{}>;
        deleteAllCriteria: () => ng.IPromise<{}>;
        clearResultOutput: () => ng.IPromise<{}>;
        refreshResultOutputs: () => ng.IPromise<{}>;
        resultOutputPaged: Common.PagedList<ResultOutput>;
        resultOutputFilter: ResultOutputFilter;
        resultOutputOrderBy: string;
        resultOutputOrderByAscending: boolean;
        toggleResultOutputOrder: (orderBy: string) => void;
        computeResultOutputFilterIsValid: () => void;
        predefinedCols: any;
        filterResultOutput: (criteria) => any;
        isCriteriaValid: (criteria) => any;
        isNamedCriteriaValid: (name, companyCriterias) => any;
        getCriteriaClassName: (isValid) => any;
        saveFilter: (saveNew: boolean) => void;

        isSelectionValid: () => boolean;

        screenOnAnyInvolvementChecked: () => void;
        screenOnAnyInvolvementUncheck: () => void;
        typeFourHasAnyInvolvement: (selectedCriteria: SelectedCriteriaDto) => boolean;

        asyncLoadSavedFilter: Sustainalytics.Common.AsyncHttpOperation<any>;
        loadSavedFilter: (filter: Filter, requiresConfirmation: boolean) => any;
        loadUniverses: () => void;
        isLatestDropDownOpen: boolean;
        selectPortfolio: any;
        selectUniverse: any;
        selectPortfolioOrUniverse: any;

        selectPeerGroup: any;
        selectRegion: any;
        selectCountry: any;
        selectCompanyType: any;

        openSavePortfolio: () => void;
        cancel: () => void;
        resultOutputIsValidVisible: boolean;
        openFilterContainer: () => void;
        hideFilterContainer: () => void;
        selectedCriteriaIsrunning: boolean;
        exportScreeningDetails: ExportDetailsDto;
        hasPortfolioPermision: boolean;
        getTemplateCriteriaClass: (isActive: boolean, isEnabled: boolean) => string;

        asyncLoadStandardFilter: Sustainalytics.Common.AsyncHttpOperation<any>;
        loadStandardFilter: (standardFilterType: StandardFilter, requiresConfirmation: boolean) => any;

        accountUniverses: Universe[];
        accountUniverseSelected: (universeId: number) => void;
        accountPortfolioSelected: (portfolioId: string) => void;
        accountUniverseId: number;
       
        universeSearchText: any;

        accountPortfoliosOrUniverseSelected: (portfolioOrUniverseId: number) => void;
        accountPortfolioOrUniverseId: number;
                        
        portfolioId: string;   

        rootPeerGroupSelected: (criteriaPeerGrouId: string) => void;
        crtPeerGroupId: string;   
        
        regionSelected: (criteriaRegionName: string) => void;
        regionId: string;         
  
        countrySelected: (criteriaCountryName: string) => void;
        countryId: string;     

        companyTypeSelected: (criteriaCompanyTypeId: number) => void;
        companyTypeId: number;     
    }

    class ScreeningToolController {
        constructor(
            private $scope: IScreeningToolControllerScope,
            $rootScope,
            $q: ng.IQService,
            $modal: Common.IModal,
            notificationFactory: Common.INotificationFactory,
            staticObjects: Common.IStaticObjects,
            screeningToolFactory: IScreeningToolFactory,
            private PortfolioService: Sustainalytics.Portfolio.PortfolioService,
            $timeout) {

            if ($rootScope['userInfo'] == null) {
                $rootScope['userInfo'] = angular.fromJson(localStorage.getItem('sust_userInfo'));
            }

            if ($rootScope['userInfo'] == null) {
                staticObjects.redirectToLogin();
                return;
            }
            
            $scope.tool = { template: 'Views/Tools/ScreeningTool/ScreeningTool.html' };
            $scope.currentSelection = "";
            $scope.isLatestDropDownOpen = false;
            $scope.baseCriteriaList = [];

            $scope.currentPortfolio = { id: "", name: "" };
            $scope.currentUniverse = { id: "", name: "" };
            $scope.currentPortfolioOrUniverse = { id: "", name: "" };

            $scope.currentPeerGroup = { id: "", name: "" };
            $scope.currentRegion = { id: "", name: "" };
            $scope.currentCountry = { id: "", name: "" };
            $scope.currentCompanyType = { id: "", name: "" };
            
            this.PortfolioService = PortfolioService;
            $scope.hasPortfolioPermision = this.PortfolioService.hasPermision();
            $scope.getTemplateCriteriaClass = (isActive, isEnabled) => {
                var className = "";

                if (isActive)
                    className = "active";

                if (!isEnabled && isEnabled != undefined)
                    className = "disabled";

                return className;
            };
            var buildGcSelectedItemsText: () => void;

            $scope.selectPortfolio = (selectedPortfolio) => {
                if ($scope.currentPortfolio != selectedPortfolio) {
                    $scope.currentPortfolio = selectedPortfolio;
                    
                    $rootScope['screeningExportDetails'].SelectedPortfolio = selectedPortfolio;
                    
                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            $scope.selectUniverse = (selectedUniverse) => {
                if ($scope.currentUniverse != selectedUniverse) {
                    $scope.currentUniverse = selectedUniverse;

                    $rootScope['screeningExportDetails'].SelectedUniverse = selectedUniverse;

                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            $scope.selectCompanyType = (selectedCompanyType) => {
                if ($scope.currentCompanyType != selectedCompanyType) {
                    $scope.currentCompanyType = selectedCompanyType;
                    $scope.companyTypeId = selectedCompanyType.intId;

                    $rootScope['screeningExportDetails'].SelectedCompanyType = selectedCompanyType;

                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            $scope.selectCountry = (selectedCountry) => {
                if ($scope.currentCountry != selectedCountry) {
                    $scope.currentCountry = selectedCountry;
                    $scope.countryId = selectedCountry.id;

                    $rootScope['screeningExportDetails'].SelectedCountry = selectedCountry;

                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            $scope.selectPeerGroup = (selectedPeerGroup) => {
                if ($scope.currentPeerGroup != selectedPeerGroup) {
                    $scope.currentPeerGroup = selectedPeerGroup;
                    $scope.crtPeerGroupId = selectedPeerGroup.id;

                    $rootScope['screeningExportDetails'].SelectedPeerGroup = selectedPeerGroup;

                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            $scope.selectRegion = (selectedRegion) => {
                if ($scope.currentRegion != selectedRegion) {
                    $scope.currentRegion = selectedRegion;
                    $scope.regionId = selectedRegion.id;

                    $rootScope['screeningExportDetails'].SelectedRegion = selectedRegion;

                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };



            $scope.selectPortfolioOrUniverse = (selectedPortfolioOrUniverse) => {
                if ($scope.currentPortfolioOrUniverse != selectedPortfolioOrUniverse) {
                    $scope.currentPortfolioOrUniverse = selectedPortfolioOrUniverse;                    

                    if (selectedPortfolioOrUniverse.isPortfolio) {

                        $rootScope['screeningExportDetails'].SelectedPortfolio = selectedPortfolioOrUniverse;
                        $scope.currentPortfolio = selectedPortfolioOrUniverse;
                        
                        $scope.currentUniverse = undefined;
                        $scope.portfolioId = selectedPortfolioOrUniverse.id;                        
                        $scope.accountUniverseId = 0;
                    }
                    else {
                        $scope.currentUniverse = selectedPortfolioOrUniverse;
                        $rootScope['screeningExportDetails'].SelectedUniverse = selectedPortfolioOrUniverse;

                        $scope.currentPortfolio = undefined;
                        $scope.accountUniverseId = selectedPortfolioOrUniverse.universeId;                        
                        $scope.portfolioId = undefined;
                    }                   

                    refreshSelectedCriteriaCompaniesCount();
                    $scope.clearResultOutput();
                }
            };

            $scope.allCriteriaComputed = function () {
                var returnValue = false;
                if ($scope.currentFilter == undefined)
                    return false;
                if ($scope.currentFilter.selectedCriteria == undefined || $scope.currentFilter.selectedCriteria.length == 0)
                    return false;


                returnValue = $scope.currentFilter.selectedCriteria.every((item) => {
                    return item.companyCount != undefined;
                });

                return returnValue;
            };

            var refreshSelectedCriteriaCompaniesCount = () => {

                if ($scope.currentFilter != null || $scope.currentFilter != undefined) {

                    $scope.currentFilter.selectedCriteria.forEach((filterCriteria) => {
                        filterCriteria.companyCount = null;
                        $scope.criteriaHub.server.getCompaniesCountByCriteriaType(filterCriteria.id, filterCriteria.type, $scope.currentPortfolio.id, $scope.accountUniverseId);
                    });
                }
            };

            $scope.$on("searchBoxClosed", (e, val) => {
                var inputPortfUnivVal = $('#portfolioOrUnivSearchInput').val();
                if (navigator.appVersion.indexOf("MSIE 9.") != -1) {
                    var placeholder = $('#portfolioOrUnivSearchInput').attr('placeholder');
                    if (inputPortfUnivVal == placeholder) {
                        inputPortfUnivVal = "";
                    }
                }
                if (inputPortfUnivVal == "" && inputPortfUnivVal != $scope.currentPortfolioOrUniverse.name) {
                    $scope.currentPortfolioOrUniverse = { id: "", name: "" };
                    $rootScope['screeningExportDetails'].SelectedPortfolio = undefined;
                    $rootScope['screeningExportDetails'].SelectedUniverse = undefined;
                    refreshSelectedCriteriaCompaniesCount();
                }
                
                var inputPeerGroupVal = $('#peerGroupSearchInput').val();
                if (inputPeerGroupVal == "" && inputPeerGroupVal != $scope.currentPeerGroup.name) {
                    $scope.currentPeerGroup = { id: "", name: "" };
                    $rootScope['screeningExportDetails'].SelectedPeerGroup = undefined;                    
                    refreshSelectedCriteriaCompaniesCount();
                }

                var inputRegionVal = $('#regionSearchInput').val();
                if (inputRegionVal == "" && inputRegionVal != $scope.currentRegion.name) {
                    $scope.currentRegion = { id: "", name: "" };
                    $rootScope['screeningExportDetails'].SelectedRegion = undefined;
                    refreshSelectedCriteriaCompaniesCount();
                }

                var inputCountryVal = $('#countrySearchInput').val();
                if (inputCountryVal == "" && inputCountryVal != $scope.currentCountry.name) {
                    $scope.currentCountry = { id: "", name: "" };
                    $rootScope['screeningExportDetails'].SelectedCountry = undefined;
                    refreshSelectedCriteriaCompaniesCount();
                }

                var inputCompanyTypeVal = $('#companyTypeSearchInput').val();
                if (inputCompanyTypeVal == "" && inputCompanyTypeVal != $scope.currentCompanyType.name) {
                    $scope.currentCompanyType = { id: "", name: "" };
                    $rootScope['screeningExportDetails'].SelectedCompanyType = undefined;
                    refreshSelectedCriteriaCompaniesCount();
                }
            });

            $scope.predefinedCols =
            {
                'Company': true,
                'Exchange': true,
                'Ticker': true,
                'Company name': true
            };

            $scope.filterResultOutput = (criteria) => {
                return !$scope.predefinedCols[criteria.name];
            }

            $scope.isCriteriaValid = (criteria) => {
                return criteria.isValid;
            }

            $scope.isNamedCriteriaValid = (name, companyCriterias) => {
                var isValid = true;

                $(companyCriterias).filter(function () { return this.name == name; }).each(function () {
                    var criteria = this;
                    isValid = $scope.isCriteriaValid(criteria);
                });

                return isValid;
            }

            $scope.getCriteriaClassName = (isValid) => {
                if (isValid == null) {
                    return null;
                }
                else {
                    return isValid ? 'screening-criteria-valid' : 'screening-criteria-invalid';
                }
            }

            // init result output filter
            $scope.resultOutputFilter = new ResultOutputFilter();
            $scope.resultOutputFilter.isValidEnabled = true;
            $scope.resultOutputFilter.isNotValidEnabled = true;
            $scope.resultOutputFilter.isNAEnabled = false;
            $scope.resultOutputFilter.isValid = 4;

            var setIsModified = (isModifed: boolean) => {
                if ($scope.currentFilter) {
                    $scope.currentFilter.isModified = isModifed;
                }
            };

            $scope.getResultOutput = (pageIndex, pageSize) => {
                $rootScope.loading = true;
                var def = $q.defer();

                // get pager
                var pager: Sustainalytics.Pager.PagerController = $scope['pager'];

                // If pager is not defined then abort execution.
                // Current controller is created before Pager controller.
                if (!pager) {
                    $rootScope.loading = false;
                    return;
                }


                if (pageIndex) {
                    pager.pagingOptions.pageIndex = pageIndex;
                }

                if (pageSize) {
                    pager.pagingOptions.pageSize = pageSize;
                }
                if ($scope.resultOutputFilter.filterId != null) {

                    var skip = pager.pagingOptions.pageSize * (pager.pagingOptions.pageIndex - 1);
                    var take = pager.pagingOptions.pageSize;

                    screeningToolFactory.getResultOutput($scope.resultOutputFilter, skip, take, $scope.resultOutputOrderBy, $scope.resultOutputOrderByAscending)
                        .success((result: GetRunResultDto) => {
                            var resultOutputPaged = new Sustainalytics.Common.PagedList<ResultOutput>();

                            resultOutputPaged.items = result.items;
                            resultOutputPaged.pagingOptions = pager.pagingOptions;
                            resultOutputPaged.totalItemsCount = result.count;
                            resultOutputPaged.totalPageCount = Math.ceil(result.count / pager.pagingOptions.pageSize);

                            $scope.resultOutputPaged = resultOutputPaged;
                            pager.totalItemsCount = result.count;

                            def.resolve();
                            $rootScope.loading = false;
                        }).error((data, status, headers, config, statusText) => {
                            $rootScope.loading = false;
                            notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));

                            ga('create', 'UA-4379897-6', {
                                'userId': $rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                            });

                            ga('globalAccess.send', 'exception', { 'exDescription': 'ScreeningTool: ResultOutput -> ' + staticObjects.getErrorMesageByStatusCode(status, data)});

                            def.reject();
                        });
                }
                else {
                    $rootScope.loading = false;
                    def.reject();
                }

                return def.promise;
            };

            $scope.loadBaseCriteriaList = () => {
                $rootScope['screeningExportDetails'] = new ExportDetailsDto();
                screeningToolFactory.listBaseCriteria().then(data => {
                    $scope.baseCriteriaList.length = 0;
                    angular.forEach(data, baseCriteria => {
                        $scope.baseCriteriaList.push(baseCriteria);
                    })
                }, error => {
                    //notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                });
            }

            $scope.toggleResultOutputOrder = (orderBy) => {
                var currentOrderBy = $scope.resultOutputOrderBy;

                if (orderBy === currentOrderBy) {
                    $scope.resultOutputOrderByAscending = !$scope.resultOutputOrderByAscending;
                }
                else {
                    $scope.resultOutputOrderBy = orderBy;
                    $scope.resultOutputOrderByAscending = true;
                }
            }

            // subscribe to properties which drive how result output retrieval is done
            $scope.$watch('resultOutputOrderBy', function () { $scope.getResultOutput(); });
            $scope.$watch('resultOutputOrderByAscending', function () { $scope.getResultOutput(); });
            $scope.$watch('resultOutputFilter.isValid', function () { $scope.getResultOutput(1); });
            $scope.$watch('resultOutputIsValidVisible', function () { $scope.computeResultOutputFilterIsValid(); });
            $scope.$watch('resultOutputFilter.isValidEnabled', function () { $scope.computeResultOutputFilterIsValid(); });
            $scope.$watch('resultOutputFilter.isNotValidEnabled', function () { $scope.computeResultOutputFilterIsValid(); });
            $scope.$watch('resultOutputFilter.isNAEnabled', function () { $scope.computeResultOutputFilterIsValid(); });
            $scope.computeResultOutputFilterIsValid = () => {

                var filter = $scope.resultOutputFilter;
                var isValid = null;

                if (filter['isValidEnabled'] && filter['isNotValidEnabled'] && !filter['isNAEnabled']) {
                    isValid = 4;
                }
                else {
                    if (filter['isValidEnabled']) {
                        isValid = 1;
                    }
                    else {
                        if (filter['isNotValidEnabled']) {
                            isValid = 0;
                        }
                        else {
                            if ((filter['isNAEnabled'])) {
                                isValid = -1;
                            }
                        }
                    }
                }

                if (filter['isValidEnabled'] && filter['isNAEnabled'] && !filter['isNotValidEnabled']) {
                    isValid = 2;
                }

                if (filter['isNotValidEnabled'] && filter['isNAEnabled'] && !filter['isValidEnabled']) {
                    isValid = 3;
                }

                if (filter['isNotValidEnabled'] && filter['isNAEnabled'] && filter['isValidEnabled']) {
                    isValid = null;
                }
                $scope.resultOutputFilter.isValid = isValid;
            };

            $scope.initSignalR = () => {
                //Set the hubs URL for the connection

                // Declare a proxy to reference the hub.
                $scope.criteriaHub = (<any>$.connection).selectedCriteriaManagerHub;

                //$scope.criteriaHub.connection.logging = true;

                $scope.criteriaHub.connection.url = "screeningtoolserv/signalr";
                if ($rootScope.authData && $rootScope.authData.access_token) {
                    $scope.criteriaHub.connection.qs = { "access_token": $rootScope.authData.access_token };
                }

                $scope.criteriaHub.client.setCompaniesCount = (criteriaId, count) => {
                    var emitOptions = { criteriaId: criteriaId, count: count };
                    $rootScope.$emit("setCompaniesCount", emitOptions);
                };
                var updateCount = (criteriaId, count) => {
                    for (var i = 0; i < $scope.currentFilter.selectedCriteria.length; i++) {
                        if ($scope.currentFilter.selectedCriteria[i].id == criteriaId) {
                            $scope.currentFilter.selectedCriteria[i].companyCount = count;
                            break;
                        }
                    }
                }

                $rootScope.$on("setCompaniesCount", (e, emitOptions) => {
                    $scope.$evalAsync(() => {
                        updateCount(emitOptions.criteriaId, emitOptions.count);
                    });
                });

                $scope.criteriaHub.connection.start().done(function () {
                });
            }

            // subscribe to pager events
            $scope.$on('pagerChanged', function (event, pager) {
                // get results
                if ($scope.currentFilter) {
                    $scope.getResultOutput();
                }
            });

            $scope.loadUniverses = () => {
                $scope.accountUniverseId = 0;

                screeningToolFactory.loadUniverses().success((result: Universe[]) => {
                    this.$scope.accountUniverses = result;
                }).error((error) => {
                    ga('create', 'UA-4379897-6', {
                        'userId': $rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Screening Tool: There was an error retrieving your universes.' });

                    notificationFactory.error("There was an error retrieving your universes.", "");
                });
            };

            $scope.loadBaseCriteriaList();
            $scope.initSignalR();
            $scope.loadUniverses();
            
            $scope.baseCriteriaSelected = (baseCriteria: BaseCriteria) => {
                var bCriteria =  activateTabForBaseCriteriaName(baseCriteria.name);

                $scope.selectCriteria(bCriteria);
                $scope.selectedCriteria.loading = true;

                $scope.searchText = "";
            }

            $scope.accountUniverseSelected = (universeId: number) => {
                $scope.accountUniverseId = universeId;
                if (universeId == 0)
                    $scope.currentUniverse = undefined;
                refreshSelectedCriteriaCompaniesCount();
                $scope.clearResultOutput();
            };

            $scope.accountPortfolioSelected = (portfolioId: string) => {
                $scope.portfolioId = portfolioId;
                if (portfolioId == "")
                    $scope.currentPortfolio = undefined;

                refreshSelectedCriteriaCompaniesCount();
                $scope.clearResultOutput();
            };

            $scope.rootPeerGroupSelected = (criteriaPeerGroupId: string) => {
                $scope.crtPeerGroupId = criteriaPeerGroupId;
                if (criteriaPeerGroupId == "")
                    $scope.currentPeerGroup = undefined;
               
                refreshSelectedCriteriaCompaniesCount();
                $scope.clearResultOutput();
            };

            $scope.regionSelected = (criteriaRegionId: string) => {
                $scope.regionId = criteriaRegionId;
                if (criteriaRegionId == "")
                    $scope.currentRegion = undefined;
                
                refreshSelectedCriteriaCompaniesCount();
                $scope.clearResultOutput();
            };

            $scope.countrySelected = (criteriaCountryId: string) => {
                $scope.countryId = criteriaCountryId;
                if (criteriaCountryId == "")
                    $scope.currentCountry = undefined;
                
                refreshSelectedCriteriaCompaniesCount();
                $scope.clearResultOutput();
            };

            $scope.companyTypeSelected = (criteriaCompanyTypeId: number) => {
                $scope.companyTypeId = criteriaCompanyTypeId;
                if (criteriaCompanyTypeId == 0)
                    $scope.currentCompanyType = undefined;
               
                refreshSelectedCriteriaCompaniesCount();
                $scope.clearResultOutput();
            };

            var activateTabForBaseCriteriaName = (name: string): BaseCriteria => {
                for (var i = 0; i < $scope.tabs.length; i++) {
                    var parentTab = $scope.tabs[i];
                    for (var j = 0; j < parentTab.childItems.length; j++) {
                        var childTab = parentTab.childItems[j];
                        for (var w = 0; w < childTab.baseCriteria.length; w++) {
                            var baseCriteria = childTab.baseCriteria[w];

                            if (baseCriteria.name == name) {
                                parentTab.active = true;
                                childTab.active = true;

                                return baseCriteria;
                            };
                        }
                    }
                }
            };

            var activateBaseCriteria = (name: string) => {
                for (var i = 0; i < $scope.tabs.length; i++) {
                    var parentTab = $scope.tabs[i];
                    for (var j = 0; j < parentTab.childItems.length; j++) {
                        var childTab = parentTab.childItems[j];
                        for (var w = 0; w < childTab.baseCriteria.length; w++) {
                            var baseCriteria = childTab.baseCriteria[w];

                            if (baseCriteria.name == name) {
                                baseCriteria.isActive = true;
                            } else {
                                baseCriteria.isActive = false;
                            };
                        }
                    }
                }
            };

            $scope.screenOnAnyInvolvementChecked = () => {
                if ($scope.selectedCriteria.typeFourScreenOnAnyInvolvement) {
                    $scope.selectedCriteria.typeFourCategories.forEach((category) => {
                        if (category.significantOwnershipYesNo)
                            category.isSignificantOwnership = true;
                        if (category.revenueRange.length == 0)
                            category.isInvolved = true;
                        if (category.revenueRange.length > 0)
                            category.selectedValue = category.maxValue;
                    });
                }

                $scope.selectedCriteria.typeFourScreenOnAnyInvolvement = true;
            }

            $scope.screenOnAnyInvolvementUncheck = () => {
                $scope.selectedCriteria.typeFourScreenOnAnyInvolvement = false;
            }


            $scope.typeFourHasAnyInvolvement = (selectedCriteria: SelectedCriteriaDto): boolean => {
                var returnValue = false;
                selectedCriteria.typeFourCategories.forEach((category) => {
                    if (category.revenueRange.length == 0) {
                        if (category.isInvolved || category.isSignificantOwnership)
                            returnValue = true;
                    }

                    if (category.revenueRange.length > 0) {
                        if ((category.selectedValue != undefined && category.selectedValue > 0) || category.isSignificantOwnership)
                            returnValue = true;
                    }
                });

                return returnValue;
            };

            $scope.tabChanged = (data: CriteriaTabs, lowerLevel: boolean) => {
                if (!$scope.selectedCriteria.loading)
                    $scope.currentSelection = "";

                if (data.name == 'Global Compact' && !$scope.selectedCriteria.loading) {
                    $scope.selectCriteria(data.childItems[0].baseCriteria[0]);
                }

                if (lowerLevel)
                    $scope.selectedCriteria.loading = false;
            };

            $scope.userTabChanged = (data: CriteriaTabs) => {
                $scope.currentSelection = "";
                if (data.name == 'Global Compact') {
                    $scope.selectCriteria(data.childItems[0].baseCriteria[0]);
                }
                $scope.selectedCriteria.loading = false;
            };

            $scope.sortableOptions = {
                stop: (event, ui) => {
                    //updateSelectedCriteriaOrderNumber();
                }
            };

            $scope.deleteCriteria = (criteria: SelectedCriteriaDto) => {
                setIsModified(true);
                screeningToolFactory.deleteCriteria(criteria.id).success(() => {
                    var index = $scope.currentFilter.selectedCriteria.indexOf(criteria);
                    $scope.currentFilter.selectedCriteria.splice(index, 1);
                    $scope.clearResultOutput();
                }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            };

            $scope.getTypeSevenItemName = (item: string) => {
                switch (item) {
                    case '0':
                        return 'Compliant';
                    case '1':
                        return 'Watchlist';
                    case '2':
                        return 'Non-compliant';
                }
            };

            var convertSliderValue = (value) => {
                switch (value) {
                    case 0:
                        return 0;
                    case 1:
                        return 5;
                    case 2:
                        return 4;
                    case 3:
                        return 3;
                    case 4:
                        return 2;
                    case 5:
                        return 1;
                    default:
                        return 0;
                }
            };

            screeningToolFactory.getCriteriaTabsAndTemplates().then(criteriaTabs=> {
                $scope.tabs = criteriaTabs;

                if (criteriaTabs != undefined && criteriaTabs.length > 0) {
                    for (var i = 0; i < criteriaTabs.length; i++) {
                        var level1 = criteriaTabs[i];
                        if (level1.isEnabled) {
                            if (level1.childItems != undefined && level1.childItems.length > 0) {
                                for (var j = 0; j < level1.childItems.length; j++) {
                                    var level2 = level1.childItems[j];
                                    if (level2.isEnabled) {
                                        if (level2.baseCriteria != undefined && level2.baseCriteria.length > 0)
                                            activateTabForBaseCriteriaName(level2.baseCriteria[0].name);

                                        return;
                                    }
                                }
                            }
                            else {
                                continue;
                            }
                        }
                        else {
                            continue;
                        }
                    }
                }
            }, error => {
                //notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
            });

            $scope.deleteSelectedItems = (item) => {
                var index = $scope.selectedCriteria.typeThreeSelectedItems.indexOf(item);
                if (index != -1) {
                    $scope.selectedCriteria.typeThreeSelectedItems.splice(index, 1);
                }
            };

            $scope.addItemToSelectedItems = (item) => {

                var index = $scope.selectedCriteria.typeThreeSelectedItems.indexOf(item);
                if (index == -1) {
                    $scope.selectedCriteria.typeThreeSelectedItems.push(item);
                }
            };

            $scope.loadCriteriaTypeThreeCollectionItems = (loadMore) => {
                var skip = 0;
                if (loadMore) {
                    skip = $scope.currentCriteriaTypeThree.collectionItems.length;
                }
                screeningToolFactory.getCriteriaTypeThreeCollectionItems($scope.selectedCriteria.id, $scope.currentCriteriaTypeThree.filter, loadMore, skip, 20)
                    .success((criteriaTypeThree: CriteriaTypeThree) => {
                        notificationFactory.success();
                        if (loadMore) {
                            var newItems = $scope.currentCriteriaTypeThree.collectionItems;
                            newItems.push.apply(newItems, criteriaTypeThree.collectionItems);
                            $scope.currentCriteriaTypeThree.collectionItems = newItems;
                        } else {
                            $scope.currentCriteriaTypeThree.collectionItems = criteriaTypeThree.collectionItems;
                        }
                        $scope.currentCriteriaTypeThree.collectionItemsTotalCount = criteriaTypeThree.collectionItemsTotalCount;

                    }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            };

            $scope.loadCriteriaTypeSevenCollectionItems = (loadMore) => {
                var skip = 0;
                if (loadMore) {
                    skip = $scope.currentCriteriaTypeSeven.collectionItems.length;
                }
                screeningToolFactory.getCriteriaTypeSevenCollectionItems($scope.selectedCriteria.id, $scope.currentCriteriaTypeSeven.filter, loadMore, skip, 20)
                    .success((criteriaTypeSeven: CriteriaTypeSeven) => {
                        notificationFactory.success();
                        if (loadMore) {
                            var newItems = $scope.currentCriteriaTypeSeven.collectionItems;
                            newItems.push.apply(newItems, criteriaTypeSeven.collectionItems);
                            $scope.currentCriteriaTypeSeven.collectionItems = newItems;
                        } else {
                            $scope.currentCriteriaTypeSeven.collectionItems = criteriaTypeSeven.collectionItems;
                        }
                        $scope.currentCriteriaTypeSeven.collectionItemsTotalCount = criteriaTypeSeven.collectionItemsTotalCount;

                    }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                    });
            };

            $scope.runCurrentCriteria = () => {
                $scope.selectedCriteriaIsrunning = true;
                var promise = $scope.runCriteria($scope.currentFilter.filterId);
                promise.then(function () {
                    notificationFactory.success("All criteria processed");
                    $scope.selectedCriteriaIsrunning = false;
                });

                return promise;
            };

            $scope.exportCriteria = () => {
                var modalInstance = $modal.open({
                    templateUrl: 'exportCriteria_dialog.tpl.html',
                    controller: 'ExportCurrentCriteriaResults',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        options: function () {
                            return { baseCriteriaList: $scope.baseCriteriaList, currentFilter: $scope.currentFilter }
                        }
                    }
                });

                modalInstance.result.then((item) => {
                    console.log(item.name);
                });
            }

            $scope.refreshResultOutputs = () => {
                return $scope.runCriteria($scope.currentFilter.filterId);
            };

            $scope.deleteAllCriteria = () => {
                var def = $q.defer();

                if (!confirm("Are you sure you want to clear all criteria?")) {
                    def.reject();
                    return def.promise;
                }

                setIsModified(true);

                var promise = screeningToolFactory.deleteAllCriteria($scope.currentFilter.filterId)
                    .success(() => {
                        $scope.currentFilter.selectedCriteria = new Array();
                        notificationFactory.success("All criteria cleared");
                    $scope.clearResultOutput().then(function () { def.resolve(); })['catch'](function () { def.reject(); });
                    }).error((data, status, headers, config, statusText) => {
                        notificationFactory.error("Error", staticObjects.getErrorMesageByStatusCode(status, data));
                        def.reject();
                    });

                return def.promise;
            };

            $scope.clearResultOutput = () => {

                if ($scope.currentFilter === null || $scope.currentFilter === undefined)
                    return;

                $rootScope['loading'] = true;
                var filterId = $scope.currentFilter.filterId;
                var def = $q.defer();
                var promise: ng.IPromise<{}> = screeningToolFactory.deleteResultOutput(filterId);
                promise.then(function () {
                    var pager: Sustainalytics.Pager.PagerController = $scope['pager'];
                    $scope.resultOutputPaged = null;
                    pager.totalItemsCount = 0;

                    $rootScope['loading'] = false;
                    def.resolve();
                });
                return def.promise;
            };

            $scope.open = (size) => {
                var modalInstance = $modal.open({
                    templateUrl: '/Views/Tools/ScreeningTool/loadFilterSelect_dialog.tpl.html',
                    controller: 'LoadFilterSelectModalController',
                    size: size || 'lg',
                    backdrop: 'static',
                    resolve: {
                        options: function () {
                            var requiresConfirmation = false;
                            if ($scope.currentFilter && $scope.currentFilter.isModified) {
                                requiresConfirmation = true;
                            }

                            return { requiresConfirmation: requiresConfirmation };
                        }
                    }
                });

                modalInstance.result.then((data) => {
                    if (data.item != null) {
                        if (data.item.filterId === '00000000-0000-0000-0000-000000000000')
                            $scope.loadStandardFilter(StandardFilter.StandardFilter, false);
                        else
                            $scope.loadSavedFilter(data.item, false);
                    }

                    if (data.deleteFilterAction) {
                        loadLatestFiltes();
                        for (var i = 0; i < data.deletedFilters.length; i++) {
                            if ($scope.currentFilter != null)
                                if ($scope.currentFilter.filterId == data.deletedFilters[i].filterId) {
                                    $scope.currentFilter = null;
                            }
                        }
                    }
                });
            };

            $scope.asyncLoadFiltersOperation = new Sustainalytics.Common.AsyncHttpOperation();

            var loadLatestFiltes = function () {
                if ($scope.asyncLoadFiltersOperation.executing) {
                    return;
                }
            }

            $scope.ensureLatestFilters = function (open) {
                if (!open) {
                    return;
                }
                if (!$scope.lastUsedFilters) {
                    loadLatestFiltes();
                }
            };

            $scope.openSavePortfolio = function () {
                var ctx = this;
                var modalInstance = $modal.open(
                    {
                        templateUrl: 'Views/Portfolio/savePortfolioScreeningDialog.tpl.html',
                        controller: 'PortfolioAddController',
                        size: 'lg',
                        backdrop: 'static',
                        resolve: {
                            filterId: function () {
                                return ctx.currentFilter.filterId;
                        },
                        companyId: function () {
                            return null;
                            }
                        }
                    });

                modalInstance.result.then((item) => {
                });
            };

            $scope.saveFilter = function (saveNew) {
                var modalInstance = $modal.open({
                    templateUrl: '/Views/Tools/ScreeningTool/saveFilter_dialog.tpl.html',
                    controller: 'SaveFilterModalController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        options: function () {
                            if (saveNew) {
                                return { createNew: saveNew, name: "", shared: false };
                            }
                            return { createNew: saveNew, name: $scope.currentFilter.name, shared: $scope.currentFilter.shared };
                        }
                    }

                });

                modalInstance.result.then((item) => {
                    if (!saveNew) {
                        $scope.currentFilter.name = item.name;
                        $scope.currentFilter.shared = item.shared;
                        setIsModified(false);
                    }
                    else {
                        $scope.loadSavedFilter(item, false);
                    }
                });
            };
            
            // Standard Filter
            $scope.asyncLoadStandardFilter = new Sustainalytics.Common.AsyncHttpOperation();

            $scope.loadStandardFilter = (standardFilterType: StandardFilter, requiresConfirmation: boolean) => {
                ///load selected filter
                if ($scope.asyncLoadSavedFilter.executing) {
                    return;
                }
                $scope.isLatestDropDownOpen = false;

                if (!(requiresConfirmation === false)) {
                    if ($scope.currentFilter) {
                        if ($scope.currentFilter.isModified) {
                            if (!confirm("This will overwrite your current criteria selection. Are you sure you want to continue?")) {
                                return;
                            }
                        }
                    }
                }
            }

            $scope.asyncLoadSavedFilter = new Sustainalytics.Common.AsyncHttpOperation();

            $scope.loadSavedFilter = (requestLoadFilter: Filter, requiresConfirmation: boolean) => {
                ///load selected filter
                if ($scope.asyncLoadSavedFilter.executing) {
                    return;
                }
                $scope.isLatestDropDownOpen = false;

                if (!(requiresConfirmation === false)) {
                    if ($scope.currentFilter) {
                        if ($scope.currentFilter.isModified) {
                            if (!confirm("This will overwrite your current criteria selection. Are you sure you want to continue?")) {
                                return;
                            }
                        }
                    }
                }
            }

            $scope.openFilterContainer = () => {
                if (!$scope.resultOutputPaged) {
                    return;
                }
                if ($scope.resultOutputIsValidVisible == true) {
                    $scope.resultOutputIsValidVisible = false;
                } else {
                    $scope.resultOutputIsValidVisible = true;
                }
            }

            $scope.hideFilterContainer = () => {
                $scope.resultOutputIsValidVisible = false;
            }
        }
    };

    interface ILoadFilterSelectModalScope extends ng.IScope {
        cancel: () => void;
        selectItem: (item) => void;
        asyncLoadFiltersOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        filterGroups: any;

        checkSortBy: (column: string, direction: boolean) => boolean;
        orderby: string;
        descending: boolean;
        setOrder: (columns: string) => void;
        deleteFullFilter: (filter) => void;
        deleteFilterAction: boolean;
        deletedFilters: any;
    };

    class LoadFilterSelectModalController {
        constructor(
            private $scope: ILoadFilterSelectModalScope,
            $rootScope,
            notificationFactory: Common.INotificationFactory,
            staticObjects: Common.IStaticObjects,
            screeningToolFactory: IScreeningToolFactory,
            $modal: Common.IModal,
            $modalInstance: Common.IModalInstance,
            options: any) {

            $scope.orderby = "stats.lastUsed";
            $scope.descending = true;
            $scope.filterGroups = [
                { "name": "Standard Filters", "filters": null},
                { "name": "My Filters", "filters": null },
                { "name": "Shared Filters", "filters": null }
            ];
            $scope.deleteFilterAction = false;
            $scope.deletedFilters = [];
            $scope.asyncLoadFiltersOperation = new Sustainalytics.Common.AsyncHttpOperation();

            $scope.cancel = () => {
                var data = {
                    item: null,
                    deleteFilterAction: $scope.deleteFilterAction,
                    deletedFilters: $scope.deletedFilters
                };
                console.log("modal cancel");
                $modalInstance.close(data);
            };

            $scope.selectItem = item => {

                if (options.requiresConfirmation) {
                    if (!confirm("This will overwrite your current criteria selection. Are you sure you want to continue?")) {
                        return;
                    }
                }
                var data = {
                    item: item,
                    deleteFilterAction: $scope.deleteFilterAction,
                    deletedFilters: $scope.deletedFilters
                };
                $modalInstance.close(data);
            };

            $scope.setOrder = (orderby) => {
                if (orderby === $scope.orderby) {
                    $scope.descending = !$scope.descending;
                } else {
                    if (orderby === "stats.lastUsed" || orderby === "stats.lastSaved") {
                        $scope.descending = true;
                    } else {
                        $scope.descending = false;
                    }

                }

                $scope.orderby = orderby;
            };

            $scope.checkSortBy = (value, ascending) => {
                return $scope.orderby === value && $scope.descending === !ascending;
            };

            $scope.deleteFullFilter = (filter) => {
                var message;
                if (filter.shared == true)
                    message = "Are you sure you want to delete this shared filter?";
                else
                    message = "Are you sure you want to delete this filter??";

                var modalInstanceDelete = $modal.open({
                    templateUrl: 'Views/Tools/ScreeningTool/confirmationDialog.tpl.html',
                    controller: 'ConfirmationController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve: {
                        message: function () {
                            return message;
                        }
                    }
                });
            }
        }
    };

    interface ISaveFilterModalScope extends ng.IScope {
        saveNew: boolean;
        filter: any;

        save: () => any;
        cancel: () => any;
        asyncSaveOperation: Sustainalytics.Common.AsyncHttpOperation<any>;
        form: any;
        submitted: boolean;
        errors: any;
        switchShared: () => void;
        acceptAccessConfirmation: boolean;
        requiresConfirmation: boolean;
        requiresOverwriteConfirmation: boolean;
        validateAccept: () => any;
        errorMessage: string;
        unacceptedName: boolean;
    };

    class SaveFilterModalController {
        private serverErrors = {
            validationError: 1040
        }
        constructor(private $scope: ISaveFilterModalScope, $rootScope, notificationFactory: Common.INotificationFactory, staticObjects: Common.IStaticObjects, screeningToolFactory: IScreeningToolFactory, $modalInstance: Common.IModalInstance, options: any) {
            var requiresConfirmation = (!options.createNew) && (options.shared);
            var validationErrors =
                {
                    4002: { field: "name", message: "A filter by this name already exists, please enter a unique name and press save." },
                    4001: { field: "name", message: "A filter by this name already exists, please enter a unique name and press save." },
                    4003: { field: "name", message: "The filter's name is required." },
                    4004: { filed: "name", message: "A filter name cannot be the same as a Standard Filter."}
                };
            $scope.form = {};
            $scope.submitted = false;
            $scope.errors = {};
            $scope.saveNew = options.createNew;
            $scope.filter = { originalName: options.name, name: options.name, shared: options.shared, acceptAccessConfirmation: false, filterId: null, acceptOverwrite: false };

            $scope.requiresConfirmation = (requiresConfirmation && !$scope.filter.shared);
            $scope.acceptAccessConfirmation = false;
            $scope.requiresOverwriteConfirmation = !options.createNew && options.name;

            $scope.asyncSaveOperation = new Sustainalytics.Common.AsyncHttpOperation();

            $scope.switchShared = () => {
                var shared = !$scope.filter.shared;
                $scope.filter.shared = shared;
                $scope.requiresConfirmation = requiresConfirmation && !shared;
                $scope.filter.acceptAccessConfirmation = false;
            };

            $scope.validateAccept = () => {
                $scope.form.filter.acceptAccessConfirmation.$setValidity("required", false);
            };

            $scope.save = () => {
                $scope.errorMessage = null;
                $scope.submitted = true;

                if (!$scope.filter.name) {
                    return;
                }

                if ($scope.requiresConfirmation && (!$scope.filter.acceptAccessConfirmation)) {
                    return;
                }

                if ($scope.requiresOverwriteConfirmation && (!$scope.filter.acceptOverwrite)) {
                    return;
                }

                if ($scope.asyncSaveOperation.executing) {
                    return;
                }

                if ($scope.filter.name === "Relative Analysis") {
                    $scope.unacceptedName = true;
                    return;
                }

                if ($scope.filter.name === "relative analysis") {
                    $scope.unacceptedName = true;
                    return;
                }
            };

            $scope.cancel = function () {
                $modalInstance.dismiss('cancel');
            };
        }
    };

    interface IExportCurrentCriteriaResults extends ng.IScope {
        getTypeSixCriterias: () => any;
        getTypeThreeCriterias: () => any;
        getTypeSevenCriterias: () => any;
        getExtraFilters: () => any;
        getTypeFiveCriterias: () => any;
        exportCurrentCriteria: (boolean) => any;
        getCheckedState: (string) => any;
        CheckInCurrentCriteria: (ISelectedCriteria, IBaseCriteria) => boolean;
        resetAll: () => void;

        ModifyExtraDetails: (string) => any;

        typeSix: Array<ExportDetailsFilter>;
        typeThree: Array<ExportDetailsFilter>;
        typeSeven: Array<ExportDetailsFilter>;
        typeFive: Array<IndicatorOptions>;
        indicatorOptions: boolean;
        close: () => void;
    }

    class ExportCurrentCriteriaResults {
        constructor(private $scope: IExportCurrentCriteriaResults, $rootScope, staticObjects: Common.IStaticObjects, screeningToolFactory: IScreeningToolFactory, $modelInstance: Common.IModalInstance, options: any, LongRunningTaskManagerService: Sustainalytics.LRTM.LongRunningTaskManagerService) {

            $scope.getTypeSixCriterias = () => {

                var baseCriteriaList = options.baseCriteriaList;

                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeSix = new Array<ExportDetailsFilter>();

                $.each(baseCriteriaList, (index: number, value: BaseCriteria) => {
                    if ((value.type == 6) && (value.name != "Comparative Group Average")) {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeSix.push(exportDetailsFilter);
                    }
                });
            }

            $scope.getCheckedState = (checkBoxName: string) => {
                var state = false;
                switch (checkBoxName) {
                    // Company Info Extras
                    case "Peer Group name":
                        return $rootScope['screeningExportDetails'].PeerGroup;
                    case "Region":
                        return $rootScope['screeningExportDetails'].Region = $rootScope['screeningExportDetails'].Region;
                    case "Country":
                        return $rootScope['screeningExportDetails'].Country = $rootScope['screeningExportDetails'].Country;
                    case "Market Capitalization":
                        return $rootScope['screeningExportDetails'].MarketCapitalization = $rootScope['screeningExportDetails'].MarketCapitalization;
                    case "Sedol":
                        return $rootScope['screeningExportDetails'].Sedol = $rootScope['screeningExportDetails'].Sedol;

                    // ESG Performance
                    case "Total ESG Score":
                        return $rootScope['screeningExportDetails'].TotalEsgScore;
                    case "Environment Score":
                        return $rootScope['screeningExportDetails'].EnvironmentScore;
                    case "Social Score":
                        return $rootScope['screeningExportDetails'].SocialScore;
                    case "Governance Score":
                        return $rootScope['screeningExportDetails'].GovernanceScore;
                    case "Preparedness Score":
                        return $rootScope['screeningExportDetails'].PreparednessScore;
                    case "Disclosure Score":
                        return $rootScope['screeningExportDetails'].DisclosureScore;
                    case "Quantitative Performance Score":
                        return $rootScope['screeningExportDetails'].QuantitativePerformanceScore;
                    case "Qualitative Performance Score":
                        return $rootScope['screeningExportDetails'].QualitativePerformanceScore;

                    // Standard Indicators
                    case "Answer Category":
                        return $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories;
                    case "Raw Score":
                        return $rootScope['screeningExportDetails'].StandardIndicatorRawScores;
                    case "Weighted Score":
                        return $rootScope['screeningExportDetails'].StandardIndicatorWeights;
                    default:
                        break;
                }
            }
            $scope.getTypeFiveCriterias = () => {
                var baseCriteriaList = options.baseCriteriaList;

                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeFive = new Array<IndicatorOptions>();

                var indicatorOptionsList = new Array<string>();
                
                indicatorOptionsList.push('Raw Score');
                indicatorOptionsList.push('Weighted Score');
                indicatorOptionsList.push('Answer Category');

                for (var i = 0; i < indicatorOptionsList.length; i++) {
                    var indicatorOptions = new IndicatorOptions();

                    indicatorOptions.name = indicatorOptionsList[i];
                    indicatorOptions.isDisabled = false;

                    $scope.typeFive.push(indicatorOptions);
                }

                $.each(currentFilter,(index: number, value: SelectedCriteriaDto) => {
                    if (value.type == 5) {
                        $scope.indicatorOptions = true;
                        
                        return;
                    }
                });


            }

            $scope.getTypeThreeCriterias = () => {

                var baseCriteriaList = options.baseCriteriaList;
                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeThree = new Array<ExportDetailsFilter>();
                $.each(baseCriteriaList, (index: number, value: BaseCriteria) => {

                    if ((value.type == 3) && (
                        value.name == "Peer Group name" || // c357e4f0-a840-4df2-fa4e-1099024a7680 Peer Group Name
                            value.name == "Region" || // d0d36a30-844f-40d2-5d04-91b3aff5a776 Region
                            value.name == "Country")) // 7c713e99-c525-480f-ba32-cd79fcb855dc Sedol
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeThree.push(exportDetailsFilter);
                    }

                    if ((value.type == 1) && (value.id == "Market Capitalization")) // 66a14c85-5e13-463e-f898-55318c447ff1 Market Cap.
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeThree.push(exportDetailsFilter);
                    }

                });

                if (!$rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories &&
                    !$rootScope['screeningExportDetails'].StandardIndicatorWeights &&
                    !$rootScope['screeningExportDetails'].StandardIndicatorRawScores)
                    $rootScope['screeningExportDetails'].StandardIndicatorRawScores = true;
            }

            $scope.getTypeSevenCriterias = function () {

                var baseCriteriaList = options.baseCriteriaList;
                var currentFilter = options.currentFilter.selectedCriteria;

                $scope.typeSeven = new Array<ExportDetailsFilter>();
                $.each(baseCriteriaList, (index: number, value: BaseCriteria) => {

                    if ((value.type == 7) && (
                        value.name == "Peer Group name" || // c357e4f0-a840-4df2-fa4e-1099024a7680 Peer Group Name
                        value.name == "Region" || // d0d36a30-844f-40d2-5d04-91b3aff5a776 Region
                        value.name == "Country"))  // 7c713e99-c525-480f-ba32-cd79fcb855dc Sedol
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeSeven.push(exportDetailsFilter);
                    }

                    if ((value.type == 1) && (value.id == "Market Capitalization"))   // 66a14c85-5e13-463e-f898-55318c447ff1 Market Cap.
                    {
                        var exportDetailsFilter = new ExportDetailsFilter();

                        exportDetailsFilter.baseCriteriaList = value;

                        exportDetailsFilter.isDisabled = $scope.CheckInCurrentCriteria(currentFilter, value);

                        $scope.typeSeven.push(exportDetailsFilter);
                    }

                });

            }

            $scope.getExtraFilters = function () {


                $scope.getTypeSixCriterias();
                $scope.getTypeThreeCriterias();
                $scope.getTypeSevenCriterias();
                $scope.getTypeFiveCriterias();
            }

            $scope.CheckInCurrentCriteria = (currentFilter: SelectedCriteriaDto, baseCriteriaList: BaseCriteria) => {

                var isDisabled: boolean;

                $.each(currentFilter,(index: number, valueC: SelectedCriteriaDto) => {
                    if (valueC.name == baseCriteriaList.name) {
                        isDisabled = true;
                    }
                    else
                        isDisabled = false;

                    if (isDisabled)
                        return false;
                });

                return isDisabled;
            }

            $scope.exportCurrentCriteria = (asCSV: boolean) => {
                var taskNumber = 0;

                if (!asCSV) {
                    $rootScope['screeningExportDetails'].CSV = false;
                    taskNumber = 100;
                }
                else {
                    $rootScope['screeningExportDetails'].CSV = true;
                    taskNumber = 101;
                }

                var promise = LongRunningTaskManagerService.runTask('ScreeningTool_' + moment().format("DDMMYYYY"), "", taskNumber, true, null);

                $modelInstance.close("done");
            };

            $scope.resetAll = () => {
                $(":input[class=enabled]", "#form").val("").removeAttr("checked").removeAttr("selected");

                $rootScope['screeningExportDetails'].PeerGroup = $rootScope['screeningExportDetails'].PeerGroup = false;
                $rootScope['screeningExportDetails'].Region = $rootScope['screeningExportDetails'].Region = false;
                $rootScope['screeningExportDetails'].Country = $rootScope['screeningExportDetails'].Country = false;
                $rootScope['screeningExportDetails'].MarketCapitalization = $rootScope['screeningExportDetails'].MarketCapitalization = false;
                $rootScope['screeningExportDetails'].Sedol = $rootScope['screeningExportDetails'].Sedol = false;

                $rootScope['screeningExportDetails'].TotalEsgScore = $rootScope['screeningExportDetails'].TotalEsgScore = false;
                $rootScope['screeningExportDetails'].EnvironmentScore = $rootScope['screeningExportDetails'].EnvironmentScore = false;
                $rootScope['screeningExportDetails'].SocialScore = $rootScope['screeningExportDetails'].SocialScore = false;
                $rootScope['screeningExportDetails'].GovernanceScore = $rootScope['screeningExportDetails'].GovernanceScore = false;
                $rootScope['screeningExportDetails'].PreparednessScore = $rootScope['screeningExportDetails'].PreparednessScore = false;
                $rootScope['screeningExportDetails'].DisclosureScore = $rootScope['screeningExportDetails'].DisclosureScore = false;
                $rootScope['screeningExportDetails'].QualitativePerformanceScore = $rootScope['screeningExportDetails'].QualitativePerformanceScore = false;
                $rootScope['screeningExportDetails'].QuantitativePerformanceScore = $rootScope['screeningExportDetails'].QuantitativePerformanceScore = false;

                $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = false;
                $rootScope['screeningExportDetails'].StandardIndicatorRawScores = $rootScope['screeningExportDetails'].StandardIndicatorRawScores = true;
                $rootScope['screeningExportDetails'].StandardIndicatorWeights = $rootScope['screeningExportDetails'].StandardIndicatorWeights = false;
            };

            $scope.close = () => {
                $modelInstance.close("done");
            }

            $scope.ModifyExtraDetails = (extraDetail: string) => {
                switch (extraDetail) {
                    // Company Info Extras
                    case "Peer Group name":
                        $rootScope['screeningExportDetails'].PeerGroup = $rootScope['screeningExportDetails'].PeerGroup ? false : true;
                        break;
                    case "Region":
                        $rootScope['screeningExportDetails'].Region = $rootScope['screeningExportDetails'].Region ? false : true;
                        break;
                    case "Country":
                        $rootScope['screeningExportDetails'].Country = $rootScope['screeningExportDetails'].Country ? false : true;
                        break;
                    case "Market Capitalization":
                        $rootScope['screeningExportDetails'].MarketCapitalization = $rootScope['screeningExportDetails'].MarketCapitalization ? false : true;
                        break;
                    case "Sedol":
                        $rootScope['screeningExportDetails'].Sedol = $rootScope['screeningExportDetails'].Sedol ? false : true;
                        break;

                    // ESG Performance
                    case "Total ESG Score":
                        $rootScope['screeningExportDetails'].TotalEsgScore = $rootScope['screeningExportDetails'].TotalEsgScore ? false : true;
                        break;
                    case "Environment Score":
                        $rootScope['screeningExportDetails'].EnvironmentScore = $rootScope['screeningExportDetails'].EnvironmentScore ? false : true;
                        break;
                    case "Social Score":
                        $rootScope['screeningExportDetails'].SocialScore = $rootScope['screeningExportDetails'].SocialScore ? false : true;
                        break;
                    case "Governance Score":
                        $rootScope['screeningExportDetails'].GovernanceScore = $rootScope['screeningExportDetails'].GovernanceScore ? false : true;
                        break;
                    case "Preparedness Score":
                        $rootScope['screeningExportDetails'].PreparednessScore = $rootScope['screeningExportDetails'].PreparednessScore ? false : true;
                        break;
                    case "Disclosure Score":
                        $rootScope['screeningExportDetails'].DisclosureScore = $rootScope['screeningExportDetails'].DisclosureScore ? false : true;
                        break;
                    case "Quantitative Performance Score":
                        $rootScope['screeningExportDetails'].QuantitativePerformanceScore = $rootScope['screeningExportDetails'].QuantitativePerformanceScore ? false : true;
                        break;
                    case "Qualitative Performance Score":
                        $rootScope['screeningExportDetails'].QualitativePerformanceScore = $rootScope['screeningExportDetails'].QualitativePerformanceScore ? false : true;
                        break;
                        
                    // Standard Indicators
                    case "Answer Category":
                        $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories = $rootScope['screeningExportDetails'].StandardIndicatorAnswerCategories ? false : true;
                        break;
                    case "Raw Score":
                        $rootScope['screeningExportDetails'].StandardIndicatorRawScores = $rootScope['screeningExportDetails'].StandardIndicatorRawScores ? false : true;
                        break;
                    case "Weighted Score":
                        $rootScope['screeningExportDetails'].StandardIndicatorWeights = $rootScope['screeningExportDetails'].StandardIndicatorWeights ? false : true;
                        break;
                    default:
                        break;
                }
            }
        }
    }

    angular.module(screeningToolModuleName)

        .controller('ScreeningToolController', [
        '$scope', '$rootScope', '$q', '$modal', 'notificationFactory', 'staticObjects', 'screeningToolFactory', 'PortfolioService', '$timeout', ($scope, $rootScope, $q, $modal, notificationFactory, staticObjects, screeningToolFactory, PortfolioService, $timeout) =>
            new ScreeningToolController($scope, $rootScope, $q, $modal, notificationFactory, staticObjects, screeningToolFactory, PortfolioService, $timeout)
        ])
        .controller('LoadFilterSelectModalController', [
        '$scope', '$rootScope', 'notificationFactory', 'staticObjects', 'screeningToolFactory','$modal', '$modalInstance', 'options', ($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modal, $modalInstance, options) =>
            new LoadFilterSelectModalController($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modal, $modalInstance, options)
        ])
        .controller('SaveFilterModalController', [
            '$scope', '$rootScope', 'notificationFactory', 'staticObjects', 'screeningToolFactory', '$modalInstance', 'options', ($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modalInstance, options) =>
                new SaveFilterModalController($scope, $rootScope, notificationFactory, staticObjects, screeningToolFactory, $modalInstance, options)
        ])
        .controller('ExportCurrentCriteriaResults', [
            '$scope', '$rootScope', 'staticObjects', 'screeningToolFactory', '$modalInstance', 'options', 'LongRunningTaskManagerService', ($scope, $rootScope, staticObjects, screeningToolFactory, $modelInstance, options, LongRunningTaskManagerService) =>
                new ExportCurrentCriteriaResults($scope, $rootScope, staticObjects, screeningToolFactory, $modelInstance, options, LongRunningTaskManagerService)
        ]);
}
